<?php
namespace app\admin\controller;

use app\common\model\AdminUser as AdminUserModel;
use app\common\model\AuthGroup as AuthGroupModel;
use app\common\model\AuthGroupAccess as AuthGroupAccessModel;
use app\common\controller\AdminBase;
use think\facade\Config;
use think\facade\Log;
use app\api\controller\Excel;

/**
 * 管理员管理
 * Class AdminUser
 * @package app\admin\controller
 */
class AdminUser extends AdminBase
{
    protected $admin_user_model;
    protected $auth_group_model;
    protected $auth_group_access_model;

    protected function initialize()
    {
        parent::initialize();
        $this->admin_user_model        = new AdminUserModel();
        $this->auth_group_model        = new AuthGroupModel();
        $this->auth_group_access_model = new AuthGroupAccessModel();
    }



    /**
     * 管理员管理
     * @return mixed
     */
    public function index()
    {

        $admin_user_list = $this->admin_user_model->paginate(10);
        return $this->fetch('index', ['admin_user_list' => $admin_user_list,'page' => $admin_user_list->render()]);
    }

    /**
     * 添加管理员
     * @return mixed
     */
    public function add()
    {
        $auth_group_list = $this->auth_group_model->select();

        return $this->fetch('add', ['auth_group_list' => $auth_group_list]);
    }

    /**
     * 保存管理员
     * @param $group_id
     */
    public function save($group_id)
    {

        if ($this->request->isPost()) {
            $data            = $this->request->param();
            $validate_result = $this->validate($data, 'AdminUser');
            if ($validate_result !== true) {
                $this->error($validate_result);
            } else {
                $data['password'] = md5($data['password'] . Config::get('salt'));

                if ($this->admin_user_model->allowField(true)->save($data)) {
                    $auth_group_access['uid']      = $this->admin_user_model->id;
                    $auth_group_access['group_id'] = $group_id;
                    $this->auth_group_access_model->save($auth_group_access);
                    $this->success('保存成功');
                } else {
                    $this->error('保存失败');
                }
            }
        }
    }

    /**
     * 编辑管理员
     * @param $id
     * @return mixed
     */
    public function edit($id)
    {
        $admin_user             = $this->admin_user_model->find($id);
        $auth_group_list        = $this->auth_group_model->select();
        $auth_group_access      = $this->auth_group_access_model->where('uid', $id)->find();
        $admin_user['group_id'] = $auth_group_access['group_id'];

        return $this->fetch('edit', ['admin_user' => $admin_user, 'auth_group_list' => $auth_group_list]);
    }

    /**
     * 更新管理员
     * @param $id
     * @param $group_id
     */
    public function update($id, $group_id)
    {
        if ($this->request->isPost()) {
            $data            = $this->request->param();
            $validate_result = $this->validate($data, 'AdminUser');

            if ($validate_result !== true) {
                $this->error($validate_result);
            } else {
                $admin_user = $this->admin_user_model->find($id);

                $admin_user->id       = $id;
                $admin_user->username = $data['username'];
                $admin_user->status   = $data['status'];

                if (!empty($data['password']) && !empty($data['confirm_password'])) {
                    $admin_user->password = md5($data['password'] . Config::get('salt'));
                }
                if ($admin_user->save() !== false) {
                    $auth_group_access['uid']      = $id;
                    $auth_group_access['group_id'] = $group_id;
                    $this->auth_group_access_model->where('uid', $id)->update($auth_group_access);
                    $this->success('更新成功');
                } else {
                    $this->error('更新失败');
                }
            }
        }
    }

    /**
     * 删除管理员
     * @param $id
     */
    public function delete($id)
    {
        if ($id == 1) {
            $this->error('默认管理员不可删除');
        }
        if ($this->admin_user_model->destroy($id)) {
            $this->auth_group_access_model->where('uid', $id)->delete();
            $this->success('删除成功');
        } else {
            $this->error('删除失败');
        }
    }

    //导出
    public function export(){
        $name='管理员导出';
        $header=['ID','用户名','状态','创建时间','最后登录时间','最后登录IP'];
        $admin_list = $this->admin_user_model->select();
        $data = array();
        for ($i=0;$i<count($admin_list);$i++){
            $data[$i][] = $admin_list[$i]['id'];
            $data[$i][] = $admin_list[$i]['username'];
            $data[$i][] = $admin_list[$i]['status']?'启用':'禁用';
            $data[$i][] = $admin_list[$i]['create_time'];
            $data[$i][] = $admin_list[$i]['last_login_time'];
            $data[$i][] = $admin_list[$i]['last_login_ip'];
        }
//        dump($data);
        controller('api/Excel')->excelExport($name,$header,$data);
    }

    //导入
    public function import($file){
        $file = ROOT_PATH.$file;
        if(!file_exists($file)){
            exit('文件不存在');
        }
        $extension = strtolower( pathinfo($file, PATHINFO_EXTENSION) );
        //区分上传文件格式
        if($extension == 'xlsx') {
            $objReader =\PHPExcel_IOFactory::createReader('Excel2007');
            $objPHPExcel = $objReader->load($file, $encode = 'utf-8');
        }else if($extension == 'xls'){
            $objReader =\PHPExcel_IOFactory::createReader('Excel5');
            $objPHPExcel = $objReader->load($file, $encode = 'utf-8');
        }
        $excel_array = $objPHPExcel->getsheet(0)->toArray();   //转换为数组格式
        array_shift($excel_array);  //删除第一个数组(标题);
        foreach ($excel_array as $k=>$v){
            if(!$v[$k+1] || $this->admin_user_model->where('username','eq',$v[$k+1])->count()){
                continue;
            }
            $auser['username'] = $v[$k+1];
            $auser['password'] = md5('123456'.Config::get('salt'));
            $this->admin_user_model->save($auser);
        }
        $this->success('导入成功');
    }
}